package com.gzzyy.unionchain.communicate.websocket

import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft
import org.java_websocket.drafts.Draft_6455
import org.java_websocket.handshake.ServerHandshake
import java.net.URI

class WsClient(
    serverUri: URI,
    protocolDraft: Draft,
    httpHeaders: Map<String, String>?,
    connectTimeout: Int
) : WebSocketClient(serverUri, protocolDraft, httpHeaders, connectTimeout) {

    constructor(
        serverUri: URI,
        protocolDraft: Draft,
        httpHeaders: Map<String, String>
    ) : this(serverUri, protocolDraft, httpHeaders, 0)

    constructor(serverUri: URI, httpHeaders: Map<String, String>) : this(
        serverUri,
        Draft_6455(),
        httpHeaders
    )

    constructor(
        serverUri: URI,
        protocolDraft: Draft
    ) : this(serverUri, protocolDraft, null, 0)

    constructor(serverUri: URI) : this(serverUri, Draft_6455())

    var clientListener: ClientListener? = null

    override fun onOpen(handshakedata: ServerHandshake?) {
        clientListener?.onWebSocketOpen(handshakedata)
    }

    override fun onClose(code: Int, reason: String?, remote: Boolean) {
        clientListener?.onWebSocketClose(code, reason, remote)
    }

    override fun onMessage(message: String?) {
        clientListener?.onWebSocketMessage(message)
    }

    override fun onError(ex: Exception?) {
        clientListener?.onWebSocketError(ex)
    }

    interface ClientListener {
        fun onWebSocketOpen(handshakedata: ServerHandshake?)

        fun onWebSocketClose(code: Int, reason: String?, remote: Boolean)

        fun onWebSocketMessage(message: String?)

        fun onWebSocketError(ex: Exception?)
    }
}